package com.lagou.service;

import com.lagou.handler.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Service;

/**
 * 用户服务实现类
 * @author yzh
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    static {
        try {
            startServer("127.0.0.1", 8001);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String sayHello(String word) {
        System.out.println("调用成功--参数 " + word);
        return "调用成功--参数 " + word;
    }

    /**
     * 启动服务的方法
     * @param hostName
     * @param port
     * @throws InterruptedException
     */
    public static void startServer(String hostName, Integer port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
            .group(bossGroup,workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                    pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                    pipeline.addLast(new UserServerHandler());
                }
            });
        serverBootstrap.bind(hostName, port).sync();
    }

}
